//
//  AMPAuthCodeView.swift
//  LivingHelper
//
//  Created by Ampaw on 2017/9/14.
//  Copyright © 2017年 Ampaw. All rights reserved.
//

import UIKit

let countDownTime = 10   // 倒计时间

protocol AMPAuthCodeViewDelegate: NSObjectProtocol {
    func didGetAuthCode();  // 获取验证码
    func didNextJump();     // 下一步
}

class AMPAuthCodeView: UIView {
    
    // MARK: - 属性
    /// 代理
    weak var authCodeViewDelegate: AMPAuthCodeViewDelegate?
    /// 当前倒计时剩余的秒数
    private var remainingSeconds: Int = 0 {
        willSet {
            authCodeButton.setTitleColor(UIColor.lightGray, for: UIControlState.normal)
            authCodeButton.setTitle("\(newValue)秒后重发", for: UIControlState.normal)
            
            if newValue <= 0 {
                authCodeButton.setTitleColor(AMPConstants.AMPMainColor, for: UIControlState.normal)
                authCodeButton.setTitle("重获验证码", for: UIControlState.normal)
                // 关闭计时
                isCounting = false
            }
        }
    }
    /// 获取验证码 场景 1：注册；2：忘记密码
    private var authcodeType: Int?
    
    /// 计时器
    private var countdownTimer: Timer?
    
    /*
     属性观察器：监控和响应属性值的变化，每次属性被设置值的时候，都会调用属性观察器，甚至新的值与现在的值相同的时候也是如此。
     willSet: 在新的值被设置之前调用
     didSet: 在新的值被设置之后，立即调用
     */
    /// 控制计时器的，开启与关闭
    private var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1,
                                                      target: self,
                                                      selector: #selector(updateTimer(timer:)),
                                                      userInfo: nil,
                                                      repeats: true)
                remainingSeconds = countDownTime
            }else{
                // 关闭并移除 计时器
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            
            authCodeButton.isEnabled = !newValue
        }
    }
    /// 每一秒更新一次Timer
    @objc private func updateTimer(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }

    // MARK: - 构造方法
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        
//        // 准备UI
//        setUpUI()
//    }
    
    /// 自定义构造方法
    init(type: Int) {
        super.init(frame: CGRect())
        self.authcodeType = type
        // 准备UI
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 准备UI
    private func setUpUI() {
        addSubViews()
        addConstraints()
    }
    
    private func addSubViews() {
        self.addSubview(self.passportTextField)
        self.addSubview(self.authCodeView)
        
        self.authCodeView.addSubview(self.authCodeTextField)
        self.authCodeView.addSubview(self.vLine)
        self.authCodeView.addSubview(self.authCodeButton)
        
        self.addSubview(self.nextButton)
        
        self.authCodeButton.addTarget(self, action: #selector(authCodeAction), for: UIControlEvents.touchUpInside)
        self.nextButton.addTarget(self, action: #selector(nextAction), for: UIControlEvents.touchUpInside)
        
        if self.authcodeType == 1 {
            self.addSubview(self.statuteButton)
            self.statuteButton.addTarget(self, action: #selector(statuteAction), for: UIControlEvents.touchUpInside)
        }
    }
    private func addConstraints() {
        unowned let WS = self
        
        self.passportTextField.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(WS).offset(0)
            make.top.equalTo(WS).offset(30)
            make.width.equalTo(AMPConstants.AMP_SCREEN_WIDTH*0.8)
            make.height.equalTo(44)
        }
        
        self.authCodeView.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(WS).offset(0)
            make.top.equalTo(WS.passportTextField.snp.bottom).offset(20)
            make.width.height.equalTo(WS.passportTextField)
        }
        
        self.authCodeTextField.snp.makeConstraints { (make) -> Void in
            make.centerY.equalTo(WS.authCodeView.snp.centerY)
            make.left.equalTo(WS.authCodeView.snp.left).offset(30)
            make.right.equalTo(WS.vLine.snp.left)
            make.height.equalTo(WS.authCodeView.snp.height)
        }
        
        self.vLine.snp.makeConstraints { (make) -> Void in
            make.centerY.equalTo(WS.authCodeView.snp.centerY)
            make.right.equalTo(WS.authCodeButton.snp.left)
            make.width.equalTo(1)
            make.height.equalTo(44 * 0.6)
        }
        
        self.authCodeButton.snp.makeConstraints { (make) -> Void in
            make.centerY.equalTo(WS.authCodeView.snp.centerY)
            make.right.equalTo(WS.authCodeView.snp.right)
            make.width.equalTo(100)
            make.height.equalTo(WS.authCodeView.snp.height)
        }
        
        self.nextButton.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(WS).offset(0)
            make.top.equalTo(WS.authCodeView.snp.bottom).offset(20)
            make.width.height.equalTo(WS.passportTextField)
        }
        
        if self.authcodeType == 1 {
            self.statuteButton.snp.makeConstraints { (make) -> Void in
                make.top.equalTo(WS.nextButton.snp.bottom).offset(20)
                make.left.equalTo(WS.nextButton.snp.left)
                make.width.equalTo(WS.nextButton.snp.width)
                make.height.equalTo(30)
            }
        }
    }
    
    // MARK: - Event
    @objc private func authCodeAction() {
//        print(#function)
        // 关闭倒计时
        isCounting = true
        authCodeViewDelegate?.didGetAuthCode()
    }
    @objc private func nextAction() {
//        print(#function)
        authCodeViewDelegate?.didNextJump()
    }
    @objc private func statuteAction(button: UIButton) {
//        print(#function)
        //获取按钮当前文字
//        print(button.currentTitle ?? "")
        
        // 反选效果
        button.isSelected = !button.isSelected
    }
    
    // MARK: - 懒加载
    lazy var passportTextField: UITextField = {
        let passport = UITextField()
        passport.backgroundColor = UIColor.white
        passport.layer.cornerRadius = 5.0;
        passport.layer.masksToBounds = true
        passport.layer.borderColor = UIColor.white.cgColor
        passport.layer.borderWidth = 1.0
        passport.font = AMPConstants.AMP_Font14
        passport.placeholder = "请输入手机号或邮箱账号"
        passport.clearButtonMode = UITextFieldViewMode.whileEditing // 设置“清除”按钮
        passport.autocapitalizationType = UITextAutocapitalizationType.none  // 去除首字母自动大写
        
        let leftImg = UIImageView()
        leftImg.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftImg.image = UIImage(named: "login_icon_passport")
        passport.leftView = leftImg
        passport.leftViewMode = UITextFieldViewMode.always
        
        return passport
    }()
    
    lazy var authCodeView: UIView = {
        let authCodeView = UIView()
        authCodeView.backgroundColor = UIColor.white
        authCodeView.layer.cornerRadius = 5.0;
        authCodeView.layer.masksToBounds = true
        authCodeView.layer.borderColor = UIColor.white.cgColor
        authCodeView.layer.borderWidth = 1.0
        
        return authCodeView
    }()
    
    lazy var authCodeTextField: UITextField = {
        let authCode = UITextField()
        authCode.backgroundColor = UIColor.white
        authCode.font = AMPConstants.AMP_Font14
        authCode.placeholder = "请输入验证码"
        authCode.clearButtonMode = UITextFieldViewMode.whileEditing // 设置“清除”按钮
        authCode.autocapitalizationType = UITextAutocapitalizationType.none  // 去除首字母自动大写
        
        return authCode
    }()
    
    lazy var vLine: UIView = {
        let line = UIView()
        line.backgroundColor = UIColor.lightGray
        
        return line
    }()
    
    lazy var authCodeButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.white
        button.titleLabel?.font = AMPConstants.AMP_Font16
        button.setTitle("获取验证码", for: UIControlState.normal)
        button.setTitleColor(AMPConstants.AMPMainColor, for: UIControlState.normal)
        
        return button
    }()
    
    private lazy var nextButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = AMPConstants.AMPMainColor
        button.layer.cornerRadius = 5.0;
        button.layer.masksToBounds = true
        button.titleLabel?.font = AMPConstants.AMP_Font18
        button.setTitle("下一步", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.black, for: UIControlState.highlighted)
        
        return button
    }()
    
    private lazy var statuteButton: UIButton = {
        let button = UIButton(type: UIButtonType.custom)
        button.backgroundColor = UIColor.clear
        button.titleLabel?.font = AMPConstants.AMP_Font13
        // 设置Button的内容，水平左对齐显示
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        // 修改Button中的titleLabel的位置，向右偏移10
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        
        button.setImage(UIImage(named: "common_icon_normal"), for: UIControlState.normal)
        button.setImage(UIImage(named: "common_icon_selected"), for: UIControlState.selected)
        
        button.setTitle("我已同意并阅读《微助手协议》", for: UIControlState.normal)
        button.setTitleColor(AMPConstants.AMPMainColor, for: UIControlState.normal)
        
        return button
    }()

}
